<template>
  <div>
    <a-col :span="span[0]" :offset="offset[0]" class="area-ele">
      <a-tree-select v-model="values[0]" :disabled="disabled" :tree-data="province" dropdown-class-name="province" @change="loadArea" />
    </a-col>
    <a-col v-if="!onlyProvince" :span="span[1]" :offset="offset[1]" class="area-ele">
      <a-tree-select
        v-model="values[1]"
        :disabled="disabled"
        :tree-data="area"
        style="margin-top: 10px"
        dropdown-class-name="area"
        @change="submitValues"
      />
    </a-col>
  </div>
</template>

<script>
import { getArea } from "@/api/area";

export default {
  name: "AreaComponent",
  props: {
    region: { type: String, default: "" },
    onlyProvince: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    display: { type: String, default: "block" },
    offset: { type: Array, default: () => [0, 0] },
    span: { type: Array, default: () => [24, 24] }
  },
  data() {
    return {
      province: [],
      area: [],
      values: []
    };
  },
  mounted() {},
  methods: {
    loadArea(value, notResetArea) {
      if (this.onlyProvince) {
        this.submitValues();
        return;
      }
      getArea({ parentId: value }).then(res => {
        if (notResetArea === null || !(notResetArea === true)) {
          this.values[1] = "";
        }
        this.area = this.tree(res.data);
        this.submitValues();
      });
    },
    tree(array, childKey, onlyLastChild) {
      if (array === null || array.length < 1) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id + "";
        item["key"] = item.id;
        item["label"] = item.name;
        item["children"] = item[childKey];

        if (item.children) {
          item["disabled"] = onlyLastChild;
          this.tree(item.children, childKey, onlyLastChild);
        }
      });
      return array;
    },
    submitValues() {
      let region = this.values.join(",");
      if (region.lastIndexOf(",") === region.length - 1) {
        region = region.substring(0, region.length - 2);
      }
      this.$emit("update:region", region);
    }
  }
};
</script>

<style scoped>
.ant-select {
  width: 100%;
  height: 36px;
}
</style>
<style>
.province,
.area {
  max-height: 45vh !important;
}
</style>
